package org.project.api;

import lombok.extern.slf4j.Slf4j;
import org.project.api.Params.searchParams;
import org.project.api.Params.shopMesParams;
import org.project.api.Vo.DataMesVo;
import org.project.api.Vo.commodityMesVo;
import org.project.service.impl.mainServiceImpl;
import org.project.utils.Result2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: hzy
 * @Date: 2022/4/13 10:15
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping("/api")
@Validated
public class mainController {

    private final mainServiceImpl service;

    @Value("${download.FilePath}")
    private String FilePath;
    @Value("${download.FileName}")
    private String FileName;

    public mainController(mainServiceImpl service) {
        this.service = service;
    }

    /**
     * 输入关键字，获得异常商品信息
     *
     * @return
     */
    @GetMapping(value = "/search")
    Result2<List<commodityMesVo>> search(@RequestParam(defaultValue = "") String keyword,
                                         @RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "0") int toType,
                                         @RequestParam(required = false) String[] toFirst
    ) {
        searchParams params = new searchParams();
        params.setPage(page);
        params.setKeyword(keyword);
        params.setToFirst(toFirst);
        params.setToType(toType);

        log.info("params = {} ", params);
        if (params.getPage() <= 0)
            return new Result2<>(false, "页码不能小于1", null);
        List<commodityMesVo> list = service.search(params);
        return new Result2<>(true, list);
    }

    /**
     * 异常商品详细信息
     * 提供每个异常商品的详细信息
     *
     * @return
     */
    @GetMapping(value = "/commodityMes")
    Result2<Object> commodityMes(@NotEmpty(message = "商品名不能为空")
                                 @RequestParam(value = "comName") String comName) {
        log.info("comName = {}", comName);
        DataMesVo mes = service.commodityMes(comName);
        return new Result2<>(true, mes);
    }

    /**
     * # 异常店铺详细信息
     * 提供每个异常店铺的详细信息
     *
     * @return
     */
    @GetMapping(value = "/shopMes")
    Result2<Object> shopMes(
//            @Validated @RequestBody shopMesParams params
            @Validated @NotEmpty(message = "店名不能为空") @RequestParam String shopName,
            @RequestParam(defaultValue = "0") int toType,
            @Validated @RequestParam(required = false) String comName,
            @RequestParam(defaultValue = "1") int page) {
        if (page <= 0)
            return new Result2<>(false, "页码不能小于1", null);

        shopMesParams params = new shopMesParams();
        params.setShopName(shopName);
        params.setComName(comName);
        params.setToType(toType);
        params.setPage(page);
        log.info("shopMesParams = {}", params);

        Map<String, Object> map = service.shopMes(params);
        return new Result2<>(true, map);
    }

    @RequestMapping("/download")
    public String fileDownLoad(HttpServletResponse response) {

        File file = new File(FilePath + FileName);

        if (!file.exists()) {
            return "下载文件不存在";
        }

        String uid = UUID.randomUUID().toString().replace("-", "");

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + uid + ".csv");

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {

            byte[] buff = new byte[1024];

            OutputStream os = response.getOutputStream();

            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error(" 错误原因为{}", e.getMessage());
            return "fail";
        }
        return "success";
    }


}
